package com.wy.leetCode;

/**
 * @author HelloWorld
 * @create 2021/10/2 12:01
 * @email 154803771@qq.com
 */
public class CountAndSay {
    public static void main(String[] args) {
        System.out.println(countAndSayRecursive(6));
        System.out.println(countAndSay(6));
    }


    // 递归
    public static String countAndSayRecursive(int n) {
        if (n == 1) {
            return "1";
        }

        String strs = countAndSayRecursive(n - 1);
        String result = "";
        int count = 1;
        int i = 0;
        char[] charArray = strs.toCharArray();
        for ( ; i < charArray.length - 1; i++) {
            if (charArray[i] == charArray[i + 1]){
                count++;
            }else {
                result += count + "" + charArray[i];
                count = 1;
            }
        }
        result += count + "" + charArray[i];
        return result;
    }

    // 非递归
    public static String countAndSay(int n) {
        if (n == 1) {
            return "1";
        }
        String strs = "1";
        String result = "";
        for (int i = 1; i < n; i++) {
            char[] charArray = strs.toCharArray();
            int j = 0;
            result = "";
            int count = 1;
            for ( ; j < charArray.length - 1; j++) {
                if (charArray[j] == charArray[j + 1]) {
                    count++;
                } else {
                    result += count + "" + charArray[j] ;
                    count = 1;
                }
            } // 循环结束时 j = charArray.length - 1

            // 【坑】 int + char 会加的是char 对应的ASCLL码的值，因此要先转换为 字符串 => int + "" + char
            result += count + "" + charArray[j];
            strs = result;
        }

        return result;
    }
}
